package com.waiter.moximoxi.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.waiter.moximoxi.MainActivity;
import com.waiter.moximoxi.R;
import com.waiter.moximoxi.base.BaseActivity;
import com.waiter.moximoxi.bean.StoreBean;
import com.waiter.moximoxi.bean.UserInfoBean;
import com.waiter.moximoxi.constant.Constant;
import com.waiter.moximoxi.dialog.SearchHistoryDeleteDialog;
import com.waiter.moximoxi.dialog.StoreChooseDialog;
import com.waiter.moximoxi.net.API;
import com.waiter.moximoxi.utils.JsonTwoUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.yhong.aframework.listener.DefaultHintDialogListener;
import cn.yhong.aframework.listener.OkHttpSuccessListener;
import cn.yhong.aframework.listener.OnCallbackListener;
import cn.yhong.aframework.utils.AtyUtils;
import cn.yhong.aframework.utils.MyOkHttpUtils;
import cn.yhong.aframework.utils.SpUtils;
import cn.yhong.aframework.view.IBaseView;
import okhttp3.Call;

/**
 * Created by 17639 on 2020/10/14.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.login_et_username)
    EditText login_et_username;
    @Bind(R.id.login_et_pwd)
    EditText login_et_pwd;
    @Bind(R.id.login_tv)
    TextView login_tv;
    @Bind(R.id.store_choose)
    TextView store_choose;

    private StoreChooseDialog storeChooseDialog;

    private SearchHistoryDeleteDialog searchHistoryDeleteDialog;

    private int shop_id;

    private List<StoreBean> list;

    @Override
    public void initContent(Bundle savedInstanceState) {
        setContent(R.layout.activity_login);
    }

    @Override
    public void initView() {
        searchHistoryDeleteDialog = new SearchHistoryDeleteDialog(mActivity);

        list = new ArrayList<>();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        try {
//            NotificationManagerCompat manager = NotificationManagerCompat.from(mActivity);
//            boolean isOpened = manager.areNotificationsEnabled();
//
//            if (!isOpened) {
//                showPushSetDialog();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        String username = (String) SpUtils.getData(mActivity, Constant.USER_NAME, "");
        String password = (String) SpUtils.getData(mActivity, Constant.USER_PWD, "");

        login_et_username.setText(username);
        login_et_pwd.setText(password);


        getStoreList();
    }


    /**
     * 获取商店列表
     */
    private void getStoreList() {

        MyOkHttpUtils.post_CallBack(API.getshop, API.getParams(), API.getLoginHeads(), new OkHttpSuccessListener(
                (IBaseView) mActivity, "分店数据", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        JSONArray jsonObject = obj.getJSONArray("data");

                        list = JSON.parseArray(jsonObject.toString(), StoreBean.class);

                        if (list != null && list.size() > 0) {
                            shop_id = list.get(0).shop_id;

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "获取分店失败", true);
            }
        });
    }

    /**
     * 显示推送状态开关
     */
    public void showPushSetDialog() {
        searchHistoryDeleteDialog.showHintDialog2("取消", "确认", "", "检测到您没有打开通知权限，是否去打开", new DefaultHintDialogListener() {
            @Override
            public void clickConfirmButton() {
                Intent localIntent = new Intent();
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 9) {
                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    localIntent.setAction(Intent.ACTION_VIEW);
                    localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                    localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                }
                startActivity(localIntent);
            }

            @Override
            public void clickCancelButton() {
                AtyUtils.showShort(mActivity, "拒绝通知权限，将会收不到客户提醒", false);
            }
        });
    }

    @Override
    public void initData() {
        storeChooseDialog = new StoreChooseDialog(mActivity, new OnCallbackListener() {
            @Override
            public void onCallback(int type, Object... obj) {
                StoreBean storeBean = (StoreBean) obj[0];
                shop_id = storeBean.shop_id;
                SpUtils.putData(mActivity, Constant.LOGIN_STORE, shop_id);
            }
        });
    }


    @OnClick({R.id.login_tv, R.id.store_choose})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_tv://登录
                if (AtyUtils.isTextEmpty(login_et_username)) {
                    AtyUtils.showShort(mActivity, "请输入账号", false);
                    return;
                }
                if (AtyUtils.isTextEmpty(login_et_pwd)) {
                    AtyUtils.showShort(mActivity, "请输入密码", false);
                    return;
                }

                login();
                break;
            case R.id.store_choose://选择分店
                storeChooseDialog.showStoreDialog(shop_id, list);
                break;
        }
    }

    /**
     * 登录
     */
    private void login() {
        Map<String, String> params = API.getParams();
        params.put("username", AtyUtils.getText(login_et_username));
        params.put("password", AtyUtils.getText(login_et_pwd));
        params.put("device_id", API.getDeviceID(mActivity));
        params.put("shop_id", shop_id + "");
        params.put("admin_type", "3");

        MyOkHttpUtils.post_CallBack(API.login, params, API.getLoginHeads(), new OkHttpSuccessListener(
                (IBaseView) mActivity, "登录", 3) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {

                    SpUtils.putData(mActivity, Constant.USER_NAME, AtyUtils.getText(login_et_username));
                    SpUtils.putData(mActivity, Constant.USER_PWD, AtyUtils.getText(login_et_pwd));
                    UserInfoBean userInfoBean = JsonTwoUtils.parseJson(response, UserInfoBean.class).get(0);
                    userInfoBean.saveInfo(mActivity);
                    startActivity(new Intent(mActivity, MainActivity.class));
                    finish();
                }
            }

            @Override
            public void onErrorResponse() {

            }
        });
    }
}
